import json
import sys
import requests

from config import getConfigParams
from requestUrl import getDocByUrl,getEntryIdByUrl
from formatContent import formatContent, removeSrcParams
from logs import saveLog

# 获取配置参数
configParams = getConfigParams(sys.argv)
url = configParams['real_url']
env = configParams['env']

# 获取文章ID
entryId = getEntryIdByUrl(configParams['base_url'])
articleId = entryId

# 单作者 2020年
# url = 'https://sspai.com/post/61551'
# 多作者 2019年
# url = 'https://sspai.com/post/61551'

headers = {
    'referer': 'https://sspai.com',
}

# 请求文章详情接口，获取主作者和联合作者
authors = []
response = requests.get(url='https://sspai.com/api/v1/article/info/get?id=' + str(articleId) +'&view=second', headers=headers)
articleInfo = json.loads(response.text)
# 主作者
authors.append(articleInfo['data']['author']['nickname'])
# 联合作者
for item in articleInfo['data']['author_seconds']:
    if item['nickname']:
        authors.append(item['nickname'])

# 获取html文本doc，得到pq对象
doc = getDocByUrl(url, headers)

# 封面图
coverUrl = doc('.article-banner img').attr('src')
if doc('.video-banner'):
    styleStr = doc('.video-banner').attr('style')
    styleList = styleStr.split(';')
    for style in styleList:
        if style.find('background') >= 0 and style.find('url(http') >= 0:
            start = style.find('url(http')
            end = style.find(') ')
            coverUrl = style[start + 4:end]

# 标题
title = doc('.article-info .title').html()
if (title == None):
    title = doc('#article-title').text()

# 文章正文
# 并将图片？后的参数去掉，否则无图
articleContent = removeSrcParams(doc('.article-body .content')).html()

# 文章作者
authorName = doc('.nickname').text()

# 时间：Y年m月d日 或 m月d日
# 格式化为Y-m-d
response = requests.get(url='https://sspai.com/api/v1/article/info/get?id=' + str(articleId) + '&view=second',
                        headers=headers)
articleData = json.loads(response.text)
publicTime = articleData['data']['released_time']

# 去【李世泉】那里过滤标签
content = formatContent(articleContent, env=env)

result = {
    'entry_id': entryId,
    'not_format_content': articleContent,
    'content': content,
    'author_name': authors[0],
    'coAuthor': authors[1:],
    'cover_url': coverUrl,
    'public_time': publicTime,
    'description': '',
    'title': title,
}
logData = {
    'params': sys.argv,
    'result': result
}
saveLog(json.dumps(logData, ensure_ascii=False))
# 结果输出
print(json.dumps(result, ensure_ascii=False))
